package com.common.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;



/**
 * 五笔拼音生成工具类 . 说明:chinese_font.txt字库中，如：蝶dj中,第一个字蝶表示汉字，第二个字d表示拼音码，第三个字j表示五笔码
 * 添加字库时请一行一行添加
 * <pre>
 *      String pycode=PyWbUtil.getPyCode ("中国");
 *      String wbcode=PyWbUtil.getWbCode ("中国");
 *      如果字库中没有，则 生成对应的拼音或者五笔码为空("")
 * </pre>
 */
public final class PyWbUtil
{

    /**
     * 日志记录器.
     */
    private static final Logger logger = LoggerFactory.getLogger (PyWbUtil.class.getName ());

    private static Map s_chineseFont;
    private final static int WB = 1;
    private final static int PY = 0;

    private final static int KEY_BEGIN = 0;
    private final static int KEY_END = 1;

    private final static int VALUE_BEGIN = 1;
    private final static int VALUE_END = 3;

    static
    {
        s_chineseFont = readChineseFont ();
    }

    private PyWbUtil ()
    {

    }

    /**
     * @param input 输入字符.
     * @return String
     */
    public static String getWbCode (String input)
    {
//        logger.info ("before call PyWbUtil.getWbCode(String input):" + input);
        return getCode (input, WB);
    }

    /**
     * @param input 输入字符.
     * @return String
     */
    public static String getPyCode (String input)
    {
//        logger.info ("before call PyWbUtil.getWbCode(String input):" + input);
        return getCode (input, PY);
    }

    /**
     * 读font.txt中文字库.
     *
     * @return
     */
    private static Map readChineseFont ()
    {
        logger.info ("call PyWbUtil.readChineseFont () begin... ...");
        BufferedReader br = null;
        Map <String, String> o = new HashMap <String, String> ();
        try
        {
            br = new BufferedReader (new InputStreamReader (PyWbUtil.class.getResourceAsStream ("/chinese_font.txt"),Charset.forName("utf-8")));
            String temp;
            while ((temp = br.readLine ()) != null)
            {
                temp = temp.trim ();
                o.put (temp.substring (KEY_BEGIN, KEY_END), temp.substring (VALUE_BEGIN, VALUE_END));
            }
        }
        catch (Exception e)
        {
            logger.info ("call PyWbUtil.readChineseFont () is error:" + e.getMessage ());
            e.printStackTrace ();
        }
        finally
        {
            try
            {
                if(br!=null)
                {
                    br.close ();
                }
            }
            catch (IOException e)
            {
                logger.info ("call PyWbUtil.readChineseFont () is error:" + e.getMessage ());
                e.printStackTrace ();
            }
        }
        logger.info ("call PyWbUtil.readChineseFont () end... ...");
        return o;
    }

    /**
     *
     * @param input 输入字符 .
     * @param flag 0拼音,1五笔 .
     * @return String
     */
    private static String getCode (String input, int flag)
    {
//        logger.info ("before call getCode(String input):" + input);
        if (input == null)
        {
            return "";
        }
        //剔除非中文字符后，如果为空，则返回空字符串
        input = extractionChinese(input);
        if(input.isEmpty ())
        {
            return "";
        }

        StringBuffer wb = new StringBuffer ();
        try
        {
            //int chineseFontLength = s_chineseFont != null ? s_chineseFont.size () : 0;
            if (s_chineseFont == null || s_chineseFont.isEmpty ())
            {
                readChineseFont ();
            }
            if (s_chineseFont == null || s_chineseFont.isEmpty ())
            {
                logger
                        .info ("readChineseFont is failure" + ",please check PyWbUtil.jar classpath  chinese_font.txt!!!");
                throw new Exception ("readChineseFont is failure"
                        + ",please check PyWbUtil.jar classpath  chinese_font.txt!!!");
            }

            char[] words = input.toCharArray ();
            for (int i = 0; i < words.length; i++)
            {
                String key=String.valueOf (words[i]);
                Object value = s_chineseFont.get (key);
                String pywbCode = value == null ? "" : String.valueOf (value);
                try
                {
                    wb.append ((pywbCode != null && !"".equals (pywbCode)) ? pywbCode.charAt (flag) : key);
                }
                catch (Exception e)
                {
                    logger.info ("call PyWbUtil.getWbCode(String input) is error:" + e.getMessage () + "PywbCode is:"
                            + pywbCode);
                    e.printStackTrace ();
                }

            }
        }
        catch (Exception e)
        {
            logger.info ("call PyWbUtil.getWbCode(String input) is error:" + e.getMessage ());
            e.printStackTrace ();
        }
        return wb.toString ();
    }

    private static String extractionChinese(String input)
    {
        StringBuffer result = new StringBuffer(50);
        String regex = "[\u4e00-\u9fa5a-zA-Z0-9]";
        char[] array = input.trim ().toCharArray ();
        for(char single : array)
        {
            if((single+"").matches (regex))
            {
                result .append (single);
            }
        }
        return result.toString ();
    }

    /**
     * @param args
     */
    public static void main(String[] args)
    {
//        System.out.println (PyWbUtil.getPyCode ("中文｛涨｝{张}[长]【常】（方）(员)$￥(r)Z67"));
        System.out.println (PyWbUtil.getPyCode ("你好"));
        System.out.println (PyWbUtil.getWbCode ("你好"));
    }

}
